package com.example.springboot.ytest.ytool;

import com.example.springboot.ytest.bean.DoorCapability;
import com.example.springboot.ytest.bean.VehicleCapabilityElement;
import com.example.springboot.ytest.bean.WindowCapability;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author yeyi
 * @date 2021/8/23 16:57
 **/
@Slf4j
public class HttpUtil {

    /**
     * 对象属性转成 http get 请求参数
     * @return 失败返回 null
     */
    public static String makeHttpGetParam(Class clazz, Object paraObj){
        List<? extends Class<? extends Serializable>> classes =
                Arrays.asList(String.class, Integer.class, Long.class, int.class, long.class);
        StringBuilder sb = new StringBuilder();
        try {
            for (Field f : clazz.getDeclaredFields()) {
                // 过虑类型
                if (!classes.contains(f.getType())) {
                    continue;
                }

                f.setAccessible(true);
                // 过虑空值
                Object val = f.get(paraObj);
                if (null == val) {
                    continue;
                }

                sb.append(f.getName() + "=" + val + "&");
            }
        }catch (Exception e){
            log.error("getRequestStrin err: {}", e);
            return null;
        }

        return sb.substring(0,sb.length()-1);
    }

    public static String makeHttpGetParam(String url, Object paraObj){
        if (null == paraObj) {
            return url;
        }

        String para = makeHttpGetParam(paraObj.getClass(), paraObj);
        if (null == para) {
            return null;
        }

        if (StringUtils.isBlank(para)) {
            return url;
        }

        return url+"?"+para;
    }
    
    public static void main(String[] args) {
        VehicleCapabilityElement element = new VehicleCapabilityElement();
        element.setFactoryCode("factoryCode");
        element.setWindowCapabilities(Arrays.asList(new WindowCapability()));
        System.out.println(makeHttpGetParam("www.baidu.com", element));

        DoorCapability door = new DoorCapability();
        door.setDoor(222);
        door.setLockCapability(6);
        door.setOptionCapability("Hellow");
        System.out.println(makeHttpGetParam("www.baidu.com", door));
	}
}
